import React, { useEffect, useState } from 'react';
import {
  Form,
  Input,
  Button,
  Space,
  Select,
  DatePicker,
  Tooltip,
  message,
} from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { useRequest, useUpdateEffect } from '@umijs/hooks';
import { apiFileGetList, deviceMaster } from '@/services/otherServices';

const Search = (props: any) => {
  const [form] = Form.useForm();
  const { callbackValue, loading: pageLoading } = props;
  const [data, setData] = useState([]);
  const [searchValue, setSearchValue] = useState('');
  const { loading, run } = useRequest(deviceMaster, {
    manual: true,
    throttleInterval: 500,
    onSuccess: (res, params) => {
      setData(res.data);
    },
  });

  useUpdateEffect(() => {
    run({
      deviceNo: searchValue,
      pageNo: 1,
      pageSize: 10,
    });
  }, [searchValue]);

  useEffect(() => {
    run({
      pageNo: 1,
      pageSize: 10,
    });
  }, []);

  const onFinish = (values: any) => {
    if (values.deviceId === undefined) {
      message.error('请先选择设备');
      return;
    }
    if (values.dateStr) {
      values.dateStr = values.dateStr.format('YYYYMMDD');
    }
    callbackValue(values);
  };
  return (
    <Form
      style={{ display: 'flex' }}
      form={form}
      name="control-hooks"
      onFinish={onFinish}
    >
      <Space>
        <Form.Item name="deviceId" style={{ margin: 0, width: 240 }}>
          <Select
            allowClear
            style={{ width: 240, margin: 0 }}
            showSearch
            onSearch={value => {
              setSearchValue(value);
            }}
            filterOption={false}
            placeholder="选择设备"
          >
            {data &&
              data.map((item: any) => (
                <Select.Option key={item.id} value={item.deviceNo}>
                  {item.deviceNo}
                </Select.Option>
              ))}
          </Select>
        </Form.Item>
        <Form.Item name="dateStr" style={{ margin: 0, width: 240 }}>
          <DatePicker style={{ width: 240 }} allowClear />
        </Form.Item>

        <Form.Item style={{ margin: 0 }}>
          <Space>
            <Tooltip title="搜索">
              <Button
                disabled={pageLoading}
                type="primary"
                htmlType="submit"
                icon={<SearchOutlined />}
              />
            </Tooltip>
          </Space>
        </Form.Item>
      </Space>
    </Form>
  );
};

export default Search;
